package jjn.round1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jjn
 * @since 2022/9/24 09:34
 */
public class Interview_8_12_EightQueens {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>(n * n * 2);
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(board[i], '.');
        }
        backtrack(result, n, board, 0);
        return result;
    }

    private void backtrack(List<List<String>> result, int n, char[][] board, int row) {
        if (row == n) {
            List<String> snapshot = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                snapshot.add(new String(board[i]));
            }
            result.add(snapshot);
            return;
        }
        for (int column = 0; column < n; column++) {
            if (isOkay(board, n, row, column)) {
                board[row][column] = 'Q';
                backtrack(result, n, board, row + 1);
                board[row][column] = '.';
            }
        }
    }

    private boolean isOkay(char[][] board, int n, int row, int column) {
        for (int k = 0; k < n; k++) {
            if (board[k][column] == 'Q') {
                return false;
            }
        }
        int i = row - 1;
        int j = column + 1;
        while (i >= 0 && j < n) {
            if (board[i][j] == 'Q') {
                return false;
            }
            i--;
            j++;
        }
        i = row - 1;
        j = column - 1;
        while (i >= 0 && j >= 0) {
            if (board[i][j] == 'Q') {
                return false;
            }
            i--;
            j--;
        }
        return true;
    }
}
